package com.zhihuitong.meeting.global;

import android.text.TextUtils;

import com.huawei.cloudlink.openapi.api.CLMCompleteHandler;
import com.huawei.cloudlink.openapi.api.CloudLinkSDK;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.zhihuitong.meeting.login.GetHuaWeiUserInfo;
import com.zhihuitong.meeting.login.HuaWeiAuthInfo;
import com.zhihuitong.meeting.net.BaseResult;
import com.zhihuitong.meeting.net.HttpUtil;
import com.zhihuitong.meeting.net.ServiceAPI;
import com.zhihuitong.meeting.net.callback.MyCallBack;
import com.zhihuitong.meeting.utils.Base64Util;
import com.zhihuitong.meeting.utils.JsonUtil;
import com.zhihuitong.meeting.utils.MD5;

import java.util.HashMap;

/**
 * 作者： guoyuan
 * 时间 2020/2/26.
 * 文件描述：华为账号提供者
 * 版本号：V 1.0
 **/
public class HuaWeiUserProvider {

    /**
     * 获取华为云账号
     *
     * @param userName
     * @param pwd
     * @param onHuaWeiUserListener
     */
    public static void getUser(String userName, String pwd, final onHuaWeiUserListener onHuaWeiUserListener) {
        if (onHuaWeiUserListener == null) {
            return;
        }
        HttpParams map = new HttpParams();
        long currentTimeMillis = System.currentTimeMillis();
        map.put("timestamp", currentTimeMillis);
        map.put("authid", "CwiZGV2aW235");
        map.put("signature", MD5.md5("V2aWrt6" + currentTimeMillis));
        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("opType", "a");
        objectHashMap.put("userId", userName);
        objectHashMap.put("type", "1");
        objectHashMap.put("pwd", pwd);
        String value = JsonUtil.parseMapToJson(objectHashMap);
        map.put("dataJson", value);

        HttpUtil.<String>post(ServiceAPI.GET_USERID, map, ServiceAPI.GET_USERID).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (TextUtils.isEmpty(body)) {
                    onHuaWeiUserListener.onHuaWeiUserFail("数据异常");
                    return;
                }
                BaseResult baseResult = JsonUtil.parseJsonToBean(body, BaseResult.class);
                if (baseResult.success) {
                    GetHuaWeiUserInfo getHuaWeiUserInfo = JsonUtil.parseJsonToBean(body, GetHuaWeiUserInfo.class);
                    if (!TextUtils.isEmpty(getHuaWeiUserInfo.data.userId) && !TextUtils.isEmpty(getHuaWeiUserInfo.data.pwd)) {
                        onHuaWeiUserListener.onHuaWeiUserSuccess(getHuaWeiUserInfo.data.userId, getHuaWeiUserInfo.data.pwd);
                    } else {
                        onHuaWeiUserListener.onHuaWeiUserFail(baseResult.message);
                    }
                } else {
                    onHuaWeiUserListener.onHuaWeiUserFail(baseResult.message);
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                onHuaWeiUserListener.onHuaWeiUserFail(response.getException().toString());
            }
        });
    }


    /**
     * 释放华为用户账号
     * 提供者
     *
     * @param userId
     * @param pwd
     */

    public static void releaseHuaWeiUser(String userId, String pwd, final onHuaWeiUserListener onHuaWeiUserListener) {
        if (onHuaWeiUserListener == null) {
            return;
        }

        HttpParams map = new HttpParams();
        long currentTimeMillis = System.currentTimeMillis();
        map.put("timestamp", currentTimeMillis);
        map.put("authid", "CwiZGV2aW235");
        map.put("signature", MD5.md5("V2aWrt6" + currentTimeMillis));
        HashMap<String, Object> objectHashMap = new HashMap<>();
        objectHashMap.put("opType", "r");
        objectHashMap.put("userId", userId);
        objectHashMap.put("type", "1");
        objectHashMap.put("pwd", pwd);
        String value = JsonUtil.parseMapToJson(objectHashMap);
        map.put("dataJson", value);

        HttpUtil.<String>post(ServiceAPI.RELEASE_USERID, map, ServiceAPI.GET_USERID).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (TextUtils.isEmpty(body)) {
                    onHuaWeiUserListener.onHuaWeiUserFail("数据异常");
                    return;
                }
                BaseResult baseResult = JsonUtil.parseJsonToBean(body, BaseResult.class);
                if (baseResult.success) {
                    onHuaWeiUserListener.onHuaWeiUserSuccess(baseResult.message, "");
                } else {
                    onHuaWeiUserListener.onHuaWeiUserFail(baseResult.message);
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                onHuaWeiUserListener.onHuaWeiUserFail(response.getException().toString());
            }
        });
    }


    public interface onHuaWeiUserListener {
        void onHuaWeiUserSuccess(String userId, String pwd);

        void onHuaWeiUserFail(String msg);
    }


    public interface onHuaWeiUserAuthListener {
        void onHuaWeiUserAuthSuccess(String userId, HuaWeiAuthInfo.UserBean pwd);

        void onHuaWeiUserAuthFail(String msg);
    }

    /**
     * 华为云账号鉴权
     *
     * @param account
     * @param pwd
     */
    public static void huaweiAuth(final String account, final String pwd, final onHuaWeiUserAuthListener onHuaWeiUserAuthListener) {
        if (onHuaWeiUserAuthListener == null) {
            return;
        }

        String accountPwd = account + ":" + pwd;
        final String base64 = Base64Util.getBase64(accountPwd);
        HashMap<String, Object> map = new HashMap<>();
        map.put("account", account);
        map.put("clientType", 0);
        map.put("createTokenType", 0);
        HttpUtil.<HuaWeiAuthInfo>post(ServiceAPI.HUAWEI_AUTH, map, ServiceAPI.HUAWEI_AUTH)
                .headers("Authorization", "Basic " + base64)
                .execute(new MyCallBack<HuaWeiAuthInfo>() {
                    @Override
                    public void success(HuaWeiAuthInfo body) {
                        if (body != null && !TextUtils.isEmpty(body.accessToken)) {
                            onHuaWeiUserAuthListener.onHuaWeiUserAuthSuccess(body.accessToken, body.user);
                            //保存华为token
                            MyApplication.setHuaWeiToken(body.accessToken);
                            MyApplication.setUser(body.user);
                        } else {
                            onHuaWeiUserAuthListener.onHuaWeiUserAuthFail("华为云账号鉴权失败!");
                        }
                    }

                    @Override
                    public void error(String msg) {
                        onHuaWeiUserAuthListener.onHuaWeiUserAuthFail(msg);
                    }
                });
    }


    /**
     * 登陆华为云账号
     *
     * @param account
     * @param pwd
     * @param completeHandler
     */
    public static void huaWeiLogin(String account, String pwd, CLMCompleteHandler completeHandler) {
        if (completeHandler == null) {
            return;
        }
        CloudLinkSDK.getOpenApi().clmLogin(account, pwd, completeHandler);
//        CloudLinkSDK.getOpenApi().clmLogin(account, pwd,
//                new CLMCompleteHandler() {
//                    @Override
//                    public void onCompleted(CLMResult result) {
//                        if (result.getCode() == 0) {
//                            ToastUtils.showToast("登录成功");
//                            MainActivity.start(mContext);
//                        } else {
//                            Log.e("huawei", "login fail" + result.getMessage());
//                            ToastUtils.showToast("登录失败");
//                        }
//                    }
//                });
    }

    /**
     * 注销华为云账号
     *
     * @param account
     * @param pwd
     * @param completeHandler
     */
    public static void huaWeiLogout(String account, String pwd, CLMCompleteHandler completeHandler) {
        if (completeHandler == null) {
            return;
        }
        CloudLinkSDK.getOpenApi().clmLogout(completeHandler);
//        CloudLinkSDK.getOpenApi().clmLogout(new completeHandler() {
//            pubilc void onCompleted(CLMResult result) {
//                if(getActivity() != null){
//                    ((DemoActivity)getActivity()).dismissLoading();
//                }
//                if(result.getCode() == 0){
//                    DemoUtil.showToast(getContext(), "登出成功");
//                } else {
//                    DemoUtil.showToast(getContext(), result.getMessage());
//                }
//            }
//        });
    }
}
